const app = getApp()
const networkManager = require('../../utils/networkManager.js')
const moment = require('../../utils/moment.js')

const weekdayLabels = {
  '1': '周一',
  '2': '周二',
  '3': '周三',
  '4': '周四',
  '5': '周五',
  '6': '周六',
  '7': '周日'
}

const styles = {
  '0': '民族传统',
  '1': '歌剧交响',
  '2': '乐队团体',
  '3': '歌手',
  '4': 'DJ',
  '5': '其它'
}

const ticketStatus = {
  '0': '在售',
  '1': '已截止',
  '2': '售罄'
}

Page({
  data: {
    info: {},
    ticketList: [],
    ticketCount: 0,
    totalPrice: 0,
    currentTicketType: '',
    showTickets: false,
    paddingBottom: '30rpx',
    popupPaddingBottom: '0',
    ticketTypes: {
      '4': '会员票',
      '0': '早鸟票',
      '1': '预售票',
      '2': '现场票',
      '3': 'VIP票'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 修改title
    wx.setNavigationBarTitle({
      title: 'Ticket太票',
    })

    wx.getSystemInfo({ success: (res) => {
      const model = res.model
      if (model.includes('X') || model.includes('11')) this.setData({ paddingBottom: '100rpx', popupPaddingBottom: '40rpx'})
    } })

    const performanceId = decodeURIComponent(options.performanceId)
    this.setData({ performanceId })
    // this.queryMecName('6c7ed5ae99224d7a982d69687fd3a67c')
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const { performanceId} = this.data
    const { token } = wx.getStorageSync('userInfo')
    networkManager._get(`/performance/details?token=${token}&performanceId=${performanceId}`, (res) => {
      if (res && res.code === 1001) {
        wx.navigateTo({
          url: '/pages/index/index',
        })
      }

      if (res && res.code === 0) {
        const begTime = moment(res.data.beginTime)
        const endTime = res.data.endTime && moment(res.data.endTime)
        res.data.beginTime = `${begTime.format('YYYY-MM-DD')} ${weekdayLabels[begTime.isoWeekday()]} ${begTime.format('hh:mm')}`
        res.data.style = styles[res.data.style]

        if (endTime) {
          res.data.duration = endTime.diff(begTime, 'minutes')
        }
        
        this.setData({ info: res.data })
      }
    }, console.error)


    networkManager._get(`/ticket/info?performanceId=${performanceId}`, (res) => {
      if (res && res.code === 0) {
        res.data && res.data.forEach(item => {
          item.endTime = moment(item.endTime).format('YYYY.MM.DD hh:mm')
          if (item.ticketsLeft === '0') {
            item.status = '售罄'
          } else {
            item.status = ticketStatus[item.status]
          }
        })

        this.setData({ ticketList: res.data })
      }
    }, console.error)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  plus: function() {
    const { ticketCount, ticketList, currentTicketType, currentTicketCount} = this.data
    if (!currentTicketType) return wx.showToast({
      icon: 'none',
      title: '请先选择票档！',
    })

    if (ticketCount >= currentTicketCount) {
      return wx.showToast({
        icon: 'none',
        title: '没有多余的票了',
      })
    }
    if (ticketCount >= 2 && currentTicketType === '4') {
      return wx.showToast({
        icon: 'none',
        title: '每个会员，只能领取两张',
      })
    }
    if (ticketCount >= 5) {
      return wx.showToast({
        icon: 'none',
        title: '一次最多购买5张',
      })
    }

    let price = 0
    ticketList.forEach(ticket => {
      if (ticket.type === currentTicketType) price = ticket.price
    })
    const totalPrice = ((ticketCount + 1) * price).toFixed(2)
    this.setData({ticketCount: (ticketCount + 1), totalPrice})
  },

  reduce: function() {
    const { ticketCount, ticketList, currentTicketType } = this.data
    if (!currentTicketType) return wx.showToast({
      icon: 'none',
      title: '请先选择票档！',
    })
    if (ticketCount === 0) return

    let price = 0
    ticketList.forEach(ticket => {
      if (ticket.type === currentTicketType) price = ticket.price
    })
    const totalPrice = ((ticketCount - 1) * price).toFixed(2)
    this.setData({ ticketCount: ticketCount - 1, totalPrice })
  },

  chooseTicket: function (e) {
    console.log('radio发生change事件，携带value值为：', e.currentTarget.dataset.index)
    const currentTicketType = e.currentTarget.dataset.index
    const currentTicketCount = Number(e.currentTarget.dataset.count)
    const status = e.currentTarget.dataset.status

    if (status !== '在售') {
      return wx.showToast({
        icon: 'none',
        title: '此档票已结束，请选择其他票档',
      })
    }

    this.setData({ currentTicketType, totalPrice: 0, ticketCount:0, currentTicketCount })
  },

  buyTicket: function() {
    const {showTickets} = this.data
    this.setData({showTickets: !showTickets})
  },

  popupClose: function() {
    this.setData({ showTickets:  false})
  },

  getDateString: function (date) {
    console.log(date)
    return moment(date).format('YYMMDD')
  },

  pay: function (uuid) {
    const { performanceId, currentTicketType, ticketCount, totalPrice, info } = this.data
    const {token} = wx.getStorageSync('userInfo')

    if (ticketCount === 0) return wx.showToast({
      icon: 'none',
      title: '最少购买一张票',
    })

    networkManager._post_json('/ticket/order', { token, performanceId, ticketType: currentTicketType, ticketCount, totalPrice}, (res) => {
      if (res.code === 0) {
        const {orderId} = res.data

        wx.login({
          success(res) {
            if (res.code) {
              console.log(res.code)
              //发起网络请求
              networkManager._post_json('/ticket/orderPay', { token, orderId, payChannel: 'wxxcx', code: res.code }, (res) => {
                if (res.code !== 0) return wx.showToast({
                  icon: 'none',
                  title: '购票失败，请联系我们',
                })

                wx.setStorageSync(orderId, JSON.stringify(res.data))

                wx.navigateTo({
                  url: `/pages/result/result?orderId=${orderId}&title=${info.title}`,
                })
              })
            } else {
              wx.showToast({
                icon: 'none',
                title: '购票失败，请联系我们',
              })
            }
          }
        })
        
      } else {
        wx.showToast({
          icon: 'none',
          title: res.msg,
        })
      }

    }, (res) => {

      wx.showToast({
        title: '网络繁忙，请重试',
        icon: 'none',
        duration: 2000,
      })
    });
  },
})

